package com.itheima.reggie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

//用户
@Service
@Transactional
public class UserServiceImpl implements UserService {

        @Autowired
        private SmsTemplate smsTemplate;
        @Autowired
        private RedisTemplate redisTemplate;
        @Autowired
        private UserMapper userMapper;

    @Override
    public void sendMag(String phone) {
    // 1.生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        code="12345"; // TODO 开发期间验证码写死
        // 2.发送sms短信
        // smsTemplate.sendSms(phone, code); // TODO 开发期间不发送短信
        // 3.将验证码存入redis
        redisTemplate.opsForValue().set("code:"+phone, code, Duration.ofSeconds(300));
    }
    // 用户登录
    @Override
    public ResultInfo login(String phone, String code) {
        // 1.校验验证码
        // 1-1 取出redis中验证码
        String  redisCode = (String) redisTemplate.opsForValue().get("code:"+phone);
        // 1-2 比较，不一致登录失败
        //  codeFromRedis.equals(code)  会出现空指针问题
        if (!StrUtil.equals(code,redisCode)) {
            throw new CustomException("验证码不正确");
        }
        // 2.根据手机号查询数据库有无该用户
        LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
        lq.eq(User::getPhone,phone);
        //调用mapper
        User user = userMapper.selectOne(lq);
        //判断数据库是否有该用户
        if (user==null){//如果没有请创建一个
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            //将用户添加到数据库
            userMapper.insert(user);
        } else if (user.getStatus() != 1) {
            throw new CustomException("您的账号已被冻结，请联系商家处理...");
        }
        // 3.通过jwt制作token
        Map map=new LinkedHashMap();
        map.put("id",user.getId());
        map.put("phone",user.getPhone());
        String token = JwtUtil.createToken(map);
        // 4.redis存储完整user对象（敏感、1天有效期）
        redisTemplate.opsForValue().set("phone:"+user.getPhone(), user,Duration.ofDays(1) );
        // 5.清理验证码
        redisTemplate.delete("code:" + phone);
        // 6.返回token
        return ResultInfo.success(token);
    }
}
